/*
 * BufferManager.h
 *
 * Created on: 09-Oct-2009
 * Author: Atul Shukla (atul.shukla@iiitb.net)
 */
#ifndef BUFFMGR
#define BUFFMGR
#include<string.h>
#include"../common.h"
#include"ReplacementPolicy.h"
#include<map>
#include"../DiskSpaceManager/Database.h"
class BufferManager {
	ReplacementPolicy* rp;
Page* buffPool;
double size, hit;
int accessCount;
const char* databaseName;
Database* db;
map<int,int> pagemap;
map<int,int>::iterator it;
public:


	// The constructor allocates "numbuff" pages (frames) for the buffer
	// pool in main memory
	BufferManager ( Database* db,int numBuff,Status& status,char* replacementPolicy);


	// The destructor should flush all dirty pages in the buffer pool to
	// disk before shutting down.  It should also deallocate the buffer
	// pool in main memory.
	~BufferManager ();


	// Check if the page with the given ID is in the buffer pool. If it is,
	// increment its pin_count and return a pointer to this page in the
	// parameter "page". If the pin_count was 0 before the call, the page
	// was a candidate for  replacement, but is no longer a candidate.
	// If the page is not in the buffer pool, choose a frame (from the set
	// of replacement candidates) to hold this page, read the page (using
	// the appropriate DB class method), pin it, and return a pointer to the
	// page in the parameter "page".
	// Must also write out the old page in the chosen frame if it is dirty
	// before reading new page.
	Status pinPage (int pageno, Page*& page,int emptyPage=0);



	// Unpin the page in the buffer pool with the given ID.
	// Should be called with dirty==TRUE if the client has
	// modified the page. If so, this call should set the dirty bit
	// for this frame.  Furthermore, if pin_count>0, should decrement it.
	// If pin_count==0 before this call, return an error.
	Status unpinPage (int pageno, int dirty);


	// Allocate a run of pages of size "howmany" on disk and pin the first
	// page in memory in the buffer pool.
	// Call DB object to allocate the pages only if there is an available
	// frame for the first page.
	// If the buffer is full, i.e., you cannot find a frame for the first
	// page, return an error.
	Status newPage (int& firstPageNo, Page*& firstPage, int howMany=1);

	// This function should be called to delete a page on disk.
	// This function must call the DB class to deallocate the page.
	Status freePage (int pageNo);

	// Used to flush a particular page of the buffer pool to disk.
	// Should call the write_page method of the DB class.
	Status flushPage (int pageNo);

	// Flush all pages of the buffer pool to disk.
	Status flushAllPages ();
	Status close();

	//To print map of buffer
	void viewBufferStatus();

	void viewFrame(int frameNo);
	double getHitRatio();
}; //class BufMgr

namespace BufferManagerUI{

	void bmUI(BufferManager* bm,int n);
};

#endif
